import React, { useEffect, useState, useCallback, useReducer, useMemo, useRef } from "react";
import request from '../../../utils/request'
import AlertWindow from "./components/AlertWindow";
import ItemWindow from './components/ItemWindow'
import { Pagination, Button, Upload,message } from 'antd';
// import './list.css'
import styleCss from "./List.module.css"
import { useSelector } from "react-redux";
import { CodeSandboxCircleFilled, UploadOutlined } from "@ant-design/icons";
import Item from "antd/lib/list/Item";


const list_reducer = function (state, action) {
    const { type, id, result } = action
    switch (type) {
        case 'remove':
            return [...state.filter((item) => {
                return item._id != id
            })]
        // case 'removeSome'
        case 'edit':
            return [...state.map((item, idx) => {
                if (item._id === id) {
                    return result
                } else {
                    return item
                }

            })]
        case 'change':
            return [...[], ...result]
        case 'removesome':
            return [...state.filter((item) => !result.includes(item._id))]

    }

}
const ListIds_reducer = function (state, action) {
    const { type, target } = action
    const arrystate = [...state]
    switch (type) {

        case 'qtrue':
            arrystate.unshift(target)
            return [...arrystate]

        case 'qfalse':
            return [...state.filter(item => item != target)]

        case 'everytrue':
            return [...target.map(item => item._id)]

        case 'everyfalse':
            return []
    }
}

function ProjectList() {
    const [total, setTotal] = useState(0)

    const [page, setpage] = useState(1)
    const [size, setSize] = useState(10)
    const [showOrNone, setShowOrNone] = useState({ show: false, target: null, type: null, title: null, action: null })
    const [editOrNone, setEditOrNone] = useState({ show: false, target: null, type: null, idx: null, title: null, action: null })
    const [itemList, dispatch] = useReducer(list_reducer, [])
    const [ListIds, idsDisapatch] = useReducer(ListIds_reducer, [])
    const userid = useSelector((state) => state.userInfo._id)
    const {authorization} = useSelector((state) => state.userInfo)
    // console.log('p-list-authorization',authorization)


    // console.log('list-p-count',itemList,itemList.map(item=>item._id),)

    const sureOrCancel = useCallback((target, action) => {
        setShowOrNone({ ...{ show: false, target: null, type: null, title: null, action: null } })
        switch (action) {
            case 'removeSome':
                removeSome(target)
                break;
            case 'remove':
                remove(target)
                break;
        }
    }, [])
    const addOrCancel = useCallback((action) => {
        setEditOrNone({ ...{ show: false, target: null, type: null, idx: null, title: null } })

        action.type ? addOrRevise(action) : null
    }, [])

    const addOrRevise = useCallback((action) => {
        const { type, itemResult, itemIdx } = action;
        type == 'add' ?
            request.post(`/project`, {
                name: itemResult.name,
                url: itemResult.url,
                description: itemResult.description,
                accessibility: itemResult.accessibility
            }).then(({ data }) => {
                try {
                    const {code} =data
                    if (code === 201) {
                        //成功添加
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '添加成功！详情请见第一页', action: null } })
                        request.get(`/project?page=${page}&size=${size}`
                        ).then(({ data }) => {
                            try {
                                setTotal(data.data.total)
                                dispatch({
                                    type: 'change',
                                    id: null,
                                    result: [...[], ...data.data.result]
                                })
                            } catch (err) {
                            }
                        })
                    } else if (code === 400) {
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '添加失败400', action: null } })

                    } else if (code === 401) {
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '无权限此操作401', action: null } })
                    }
                } catch (err) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '未能访问服务器！', action: null } })
                }
            }) :
            request.put(`/project/${itemResult._id}`, {
                name: itemResult.name,
                url: itemResult.url,
                description: itemResult.description,
                accessibility: itemResult.accessibility
            }).then(({ data }) => {
                console.log('size', data)
                try {
                    const {code} =data
                    if (code === 201) {
                        //成功修改
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '修改成功！详情请见当前页' } })
                        dispatch({
                            type: 'edit',
                            id: itemResult._id,
                            result: itemResult
                        })
                    } else if (code === 400) {
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '修改失败400' } })
                    } else if (code === 401) {
                        setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '无权限此操作401' } })
                    }
                } catch (err) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '未能访问服务器！' } })
                }
            });
    }, [])
    const remove = useCallback((id) => {
        // setShowOrNone({...{show:true, target:null,type:'advise',title:'删除失败'}})
        //发送删除请求 *
        request.delete(`/project/${id}`
        ).then(({ data }) => {
            console.log('remove', data)
            try {
                const {code} =data
                if (code === 204) {
                    //成功删除
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '删除成功204', action: null } })
                    dispatch({
                        type: 'remove',
                        id,
                        result: null
                    })
                } else if (code === 400) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '删除失败400', action: null } })

                } else if (code === 401) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '无权限此操作401', action: null } })
                }
            } catch (err) {
                setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '未能访问服务器！', action: null } })
            }
        })


    }, [itemList])
    const removeSome = useCallback((ListIds) => {
        console.log('ListIds', ListIds)
        request.delete(`/project`, {
            data: { ids: ListIds }
        }
        ).then(({ data }) => {
            console.log(data)
            try {
                const {code} =data
                if (code === 204) {
                    //成功删除
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '删除成功204', action: null } })
                    dispatch({
                        type: 'removesome',
                        id: null,
                        result: ListIds
                    })
                } else if (code === 400) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '删除失败400', action: null } })

                } else if (code === 401) {
                    setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '无权限此操作401', action: null } })
                }
            } catch (err) {
                setShowOrNone({ ...{ show: true, target: null, type: 'advise', title: '未能访问服务器！', action: null } })
            }
        })
    }, [])

    useEffect(() => {
        request.get(`/project?page=${page}&size=${size}`
        ).then(({ data }) => {
            try {
                const {code} =data
                setTotal(data.data.total)
                dispatch({
                    type: 'change',
                    id: null,
                    result: [...[], ...data.data.result]
                })
            } catch (err) {

            }
        })
    }, [page, size])

    //导出当前页面数据
    const handledaochu = useCallback((itemList, userid) => {
        console.log('p-list_reducer', itemList, userid)
        request.post('/project/export', {
            userid,
            ids: itemList.map(item => item._id),
            type: 'xls'
            // type:'json'  指定json格式
        }, {
            responseType: 'arraybuffer'
        }).then(res => {
            var blob = new Blob([res.data], {//这个里面的data 的二进制文件 创建一个文件对象
                type: 'application/vnd.ms-excel;charset=utf-8'
            })
            var downloadElement = document.createElement('a')//创建一个a 虚拟标签
            var href = window.URL.createObjectURL(blob) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download =
                decodeURI(
                    res.headers['content-disposition'].split('filename=')[1]
                ) || '' // 下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
            message.success('导出成功')
        }).catch((res) => {
            console.log('res', res)
            //setShowOrNone({ ...{ show: true, target: ListIds, type: 'advise', title: '数据请求失败', action: null } })
        })
    }, [])
    const propsButton = {
        name: 'list',
        action: 'http://120.76.247.5:2002/api/project/import',
        headers: {
          authorization,
        },

        onChange(info){
            const msge = info.file.response?.msg
          if (info.file.status !== 'uploading') {
            console.log('info.file=>',info.file.response, 'info.fileList=>',info.fileList);
          }
          if (msge === 'success') {
            message.success(`${info.file.name} 文件上传成功`);
          } else{
            message.error(`${info.file.name} 文件上传失败.`);
          }
        },
      };

    //导入数据

    return (
        <div className="manageListCss" style={{ width: '100%', height: '100%' }}>
            <div className={styleCss.dvvdiv} style={{ float: 'right', overflow: 'visible',display:"flex",height:'32px'}}>
                <Upload {...propsButton}>
                    <Button icon={<UploadOutlined />}>上传数据</Button>
                </Upload>
                <button
                    onClick={handledaochu.bind(null, itemList, userid)}
                    title="导出当页数据"
                >导出</button>
                <button className="dvvbut"
                    style={{ cursor: "pointer" }} disabled={false}
                    onClick={() => {
                        setEditOrNone({ ...{ show: true, target: null, type: 'add', idx: null, title: '添加' } })
                    }}
                >添加</button>
                <button onClick={() => {
                    ListIds.length === 0 ?
                        setShowOrNone({ ...{ show: true, target: ListIds, type: 'advise', title: '请添加删除选项', action: null } })
                        :
                        setShowOrNone({ ...{ show: true, target: ListIds, type: 'alert', title: '是否确认批量删除', action: 'removeSome' } });
                }} >批量删除</button>
                <div className="divbox" style={{ width: 1 + 'px', height: 1 + 'px', overflow: 'visible' }}>
                    {showOrNone.show && <AlertWindow
                        title={showOrNone.title}
                        sureOrCancel={sureOrCancel}
                        target={showOrNone.target}
                        type={showOrNone.type}
                        action={showOrNone.action}
                    ></AlertWindow>}
                    {editOrNone.show && <ItemWindow
                        title={editOrNone.title}
                        addOrCancel={addOrCancel}
                        itemIdx={editOrNone.idx}
                        target={editOrNone.target}
                        type={editOrNone.type}
                    ></ItemWindow>}
                </div>
            </div>
            <div style={{ width: '100%', minHeight: '5vh', backgroundColor: '#F8F8F8' }}>
                <table style={{ width: '100%' }}>
                    <tbody>
                        <tr style={{ width: '100%' }}>
                            <th style={{ width: '1vw' }}>
                                <input
                                    onChange={(e) => {
                                        idsDisapatch({
                                            type: 'every' + e.target.checked,
                                            target: [...[], ...itemList]
                                        })
                                    }}
                                    type='checkbox'
                                    checked={(ListIds.length === itemList.length && ListIds.length != 0) ? true : false}
                                />
                            </th>
                            <th style={{ width: '2vw' }}>序号</th>
                            <th style={{ width: '4vw' }}>项目</th>
                            <th style={{ width: '16vw' }}>成员</th>
                            <th style={{ width: '12vw' }}>操作</th>
                        </tr>
                    </tbody>

                </table>
            </div>

            <div style={{ width: '100%', overflow: "auto", height: '70vh', backgroundColor: '#fff' }}>
                <table style={{ width: '100%' }}>
                    <tbody>
                        {itemList.map((item, idx) => {
                            return <tr key={item?._id} style={{ border: 1 + 'px solid #F5F5F5' }}>
                                <td>
                                    <input
                                        value={ListIds.includes(item?._id)}
                                        onChange={(e) => {
                                            idsDisapatch({
                                                type: 'q' + e.target.checked,
                                                target: item._id
                                            })
                                        }}
                                        type='checkbox'
                                        checked={ListIds.includes(item?._id)}
                                    />

                                </td>

                                <td>{((page - 1) * size) + idx + 1}</td>
                                <td style={{ cursor: "pointer" }} title='详情'
                                    onClick={() => {
                                        setEditOrNone({ ...{ show: true, target: item, type: 'read', idx, title: '详情' } })
                                    }}>
                                    <h4 >名称：{item?.name}</h4>
                                    <p>时间：{item.update_time?.replace(/T[\d\D]*$/, '')}</p>

                                </td>
                                <td><p>负责人：{'城市他'}；</p>
                                    <p>成员：{'城市他'};</p>
                                </td>
                                <td>
                                    <button onClick={() => {
                                        setEditOrNone({ ...{ show: true, target: item, type: 'edit', idx, title: '编辑' } })
                                            ;
                                    }}
                                        style={{
                                            cursor: "pointer"
                                        }}
                                    >编辑</button>
                                    <button onClick={() => {
                                        setShowOrNone({ ...{ show: true, target: item._id, type: 'alert', title: '是否确认删除', action: 'remove' } })
                                    }}
                                        style={{
                                            cursor: "pointer"
                                        }}
                                    >删除</button>
                                </td>
                            </tr>
                        })}
                    </tbody>



                </table>
            </div>
            <div style={{
                width: '100%', height: '4vh', display: "flex",
                backgroundColor: '#F8F8F8', alignItems: 'center',
                justifyContent: "space-between",
                padding: '0 2vw'
            }}>
                <div>
                    <span>总数：{total}； </span>
                </div>

                <div className={page == 1 ? styleCss.fathercss : null} id={page == 1 ? styleCss.fathercss : null} style={{ display: "flex", alignItems: "center" }}>
                    <div>页码：</div>
                    <Pagination size="small"
                        defaultCurrent={page}
                        defaultPageSize={size}
                        //失效，不得不在onChange 中修补bug
                        // hideOnSinglePage={true}
                        total={total}
                        onChange={(page, pageSize) => {
                            page <= 0 ? setpage(1) : setpage(page);
                            setSize(pageSize)
                        }}
                        showQuickJumper={true || { goButton: ReactNode }}
                    />
                </div>
            </div>

        </div>
    )
}


export default ProjectList